package utils

import (
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"strings"
)

func FormatKey(key string, keyType string) string {
	var publicHeader = fmt.Sprintf("-----BEGIN %s-----\n", keyType)
	var publicTail = fmt.Sprintf("-----END %s-----", keyType)
	splitKey := SplitKey(key, 64)
	if splitKey == "" {
		return splitKey
	} else {
		return publicHeader + splitKey + "\n" + publicTail
	}
}

func JoinKey(key string) string {
	keyList := strings.Split(key, "\n")
	var resp string
	for _, item := range keyList {
		if len(item) == 0 {
			continue
		} else if item[0] == '-' {
			continue
		} else {
			resp += item
		}
	}
	return resp
}

func SplitKey(key string, step int) string {
	length := len(key)
	if step <= 0 || length <= 0 || length <= step {
		return key
	}
	keyByte := []byte(key)
	splitCharLength := length / step
	if length%step == 0 {
		splitCharLength -= 1
	}
	resp := make([]byte, length+splitCharLength)
	pos := 0
	for i := 0; i < length; i++ {
		resp[pos] = keyByte[i]
		pos++
		if i != 0 && i%step == 0 && i != length-1 {
			resp[pos] = '\n'
			pos++
		}
	}
	return string(resp)
}

func FormatCertificate(cert string, privateKey string) (*x509.Certificate, *rsa.PrivateKey, error) {
	certBlock, _ := pem.Decode([]byte(FormatKey(cert, "CERTIFICATE")))

	privateBlock, _ := pem.Decode([]byte(FormatKey(privateKey, "PRIVATE KEY")))

	certRes, err := x509.ParseCertificate(certBlock.Bytes)
	if err != nil {
		return nil, nil, err
	}
	privateKeyRes, err := x509.ParsePKCS1PrivateKey(privateBlock.Bytes)
	if err != nil {
		return nil, nil, err
	}
	return certRes, privateKeyRes, nil
}
